<template>
  <div id="cesiumContainer" ref="cesiumContainer"></div>
  <div
    class="popover-container"
    :style="{
      top: popoverData.popoverTop + 'px',
      left: popoverData.popoverLeft + 'px',
      opacity: popoverData.popoverOpacity
    }"
  >
    <div>{{ popoverData.name }}</div>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import earthImg from '../assets/earth2.jpg'
import icon from '../assets/wind.png'
import { GlobeRotate } from '../utils/globeRotate.js'
import apngjs from '../utils/apngjs.js'
const router = useRouter()
// 设置cesium token
Cesium.Ion.defaultAccessToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzMWJlNzNkOS05MWFlLTQ0MmUtYjhjZi0yNzAyNWVhMzM1MTUiLCJpZCI6MTcyMjI4LCJpYXQiOjE2OTc1MDMyNTN9.k9q-4ocYV4t-DtBlEgeQOzxt3qa1xI5jDUNNz2Z5ZIM'

let viewer = null
let popoverStatus = ref(false)
let popoverData = ref({
  popoverTop: '',
  popoverLeft: '',
  popoverOpacity: 0,
  name: ''
})
let entityDatas = []
onMounted(() => {
  viewer = new Cesium.Viewer('cesiumContainer', {
    animation: false, //是否创建动画小器件，左下角仪表
    baseLayerPicker: false, //是否显示图层选择器
    fullscreenButton: false, //是否显示全屏按钮
    geocoder: false, //是否显示geocoder小器件，右上角查询按钮
    homeButton: false, //是否显示Home按钮
    infoBox: false, //是否显示信息框
    sceneModePicker: false, //是否显示3D/2D选择器
    selectionIndicator: false, //是否显示选取指示器组件
    timeline: false, //是否显示时间轴
    sceneMode: Cesium.SceneMode.SCENE3D, //设定3维地图的默认场景模式:Cesium.SceneMode.SCENE2D、Cesium.SceneMode.SCENE3D、Cesium.SceneMode.MORPHING
    navigationHelpButton: false, //是否显示右上角的帮助按钮
    scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
    navigationInstructionsInitiallyVisible: false,
    showRenderLoopErrors: false, //是否显示渲染错误
    orderIndependentTranslucency: false,
    imageryProvider: new Cesium.SingleTileImageryProvider({
      url: earthImg
    })
  })
  // 隐藏天空大气
  // viewer.scene.skyAtmosphere.show = false

  // Globe 对象
  let globe = viewer.scene.globe
  // 一定要为 true，否则 undergroundColor 设置无效
  globe.translucency.enabled = true
  // 基础色透明，默认是蓝色 Cesium.Color.BLUE
  globe.baseColor = Cesium.Color.BLACK
  // 地下色透明，默认是黑色 Cesium.Color.BLACK
  globe.undergroundColor = Cesium.Color.TRANSPARENT
  globe.atmosphereLightIntensity = 0
  // 隐藏天空大气层，否则最外围有一圈
  viewer.scene.skyAtmosphere.show = false

  const points = [
    {
      lon: -65.59777,
      lat: 40.03883,
      name: '德国'
    },
    {
      lon: -45.59777,
      lat: 60.03883,
      name: '中国'
    }
  ]
  points.forEach((item) => {
    loadApng(item)
  })

  // 地球球体自转
  // let globeRotate = new GlobeRotate(viewer)
  // globeRotate.start()

  var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  let mouseMove = Cesium.ScreenSpaceEventType.MOUSE_MOVE
  viewer.screenSpaceEventHandler.removeInputAction(mouseMove)
  handler.setInputAction((e) => {
    // console.log(e, 'eee')
    const pickedObject = viewer.scene.pick(e.endPosition)
    const entityData = entityDatas.find(
      (item) => item.id === pickedObject?.id?.id
    )
    if (entityData) {
      popoverData.value.popoverTop = e.endPosition.y - 30
      popoverData.value.popoverLeft = e.endPosition.x + 30
      popoverData.value.popoverOpacity = 1
      popoverData.value.name = entityData.name
      popoverStatus.value = true
    } else {
      // popoverData.value.popoverOpacity = 0
      popoverStatus.value = false
    }
  }, mouseMove)
  var handler2 = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  let leftClick = Cesium.ScreenSpaceEventType.LEFT_CLICK
  viewer.screenSpaceEventHandler.removeInputAction(leftClick)
  handler2.setInputAction((e) => {
    // console.log(e, 'eee')
    const pickedObject = viewer.scene.pick(e.position)
    const entityData = entityDatas.find(
      (item) => item.id === pickedObject?.id?.id
    )
    if (entityData) {
      router.push({
        path: '/home'
      })
    } else {
    }
  }, leftClick)
  // 创建一个线
  // const linePositions = createLineAroundEarth()
  // console.log(linePositions, 'linePositionslinePositions')
  // const lineEntity = viewer.entities.add({
  //   polyline: {
  //     positions: linePositions,
  //     width: 2,
  //     material: Cesium.Color.YELLOW
  //   }
  // })
  // console.log(lineEntity, 'lineEntityaaaaa')
  // // 创建一个圆点并让它沿着线绕地球移动
  // const circleEntity = createCircleEntity(viewer, lineEntity)
})

// 创建一条环绕地球的线
function createLineAroundEarth() {
  const positions = []
  const radius = 6371000 // 地球半径，单位：米
  const numPoints = 36000 // 线上的点数

  for (let i = 0; i < numPoints; i++) {
    const radians = (i / numPoints) * 2 * Math.PI
    const longitude = radiansToDegrees(radians)
    const latitude = 0 // 纬度为0，沿着赤道
    const height = 3000000 // 地球表面

    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
    positions.push(position)
  }

  return positions
}

// 将弧度转换为度数
function radiansToDegrees(radians) {
  return (radians * 180) / Math.PI
}

// 创建一个圆点实体并使其沿着线绕地球移动
function createCircleEntity(viewer, lineEntity) {
  const circleEntity = viewer.entities.add({
    position: lineEntity.polyline.positions[0], // 初始位置在线的起点
    point: {
      pixelSize: 10,
      color: Cesium.Color.BLUE
    }
  })
  console.log(circleEntity, 'circleEntitycircleEntity')
  const property = new Cesium.SampledPositionProperty()
  property.addSample(
    Cesium.JulianDate.now(),
    circleEntity.position.getValue(Cesium.JulianDate.now())
  )

  viewer.clock.onTick.addEventListener((clock) => {
    const time = clock.currentTime
    const newPosition = lineEntity.polyline.getPosition(time)
    property.addSample(time, newPosition)
  })

  circleEntity.position = property

  return circleEntity
}

async function loadApng(data) {
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  let blob = await loaderURL(icon)
  let arrayBuffer = await blobToArrayBuffer(blob)
  console.log(apngjs, 'apngjsapngjsapngjs')
  let apng = apngjs.parseAPNG(arrayBuffer)
  console.log(apng, 'apng')
  let player = await apng.getPlayer(ctx)
  player.play()
  // let point = [-65.59777, 40.03883]
  let entity = viewer.entities.add({
    name: data.name,
    position: Cesium.Cartesian3.fromDegrees(data.lon, data.lat),
    billboard: {
      scale: 2
    }
  })
  console.log(entity, 'entityentity')
  entityDatas.push({ id: entity.id, name: entity.name })
  entity.billboard.image = new Cesium.CallbackProperty(() => {
    return player.currentFrame.imageElement
  }, false)
}

/**
 * 加载图片资源，得到blob类型的值
 * @param {String} url
 * @returns
 */
async function loaderURL(url) {
  function createXmlHttpRequest() {
    if (window.ActiveXObject) {
      return new ActiveXObject('Microsoft.XMLHTTP')
    } else if (window.XMLHttpRequest) {
      return new XMLHttpRequest()
    }
  }
  return new Promise((resolve) => {
    let xhr = createXmlHttpRequest()
    xhr.open('get', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function (res) {
      if (this.status == 200) {
        var blob = this.response
        resolve(blob)
      }
    }
    xhr.send()
  })
}

/**
 * 将blob转换成buffer
 * @param {Blob} blob
 * @returns
 */
async function blobToArrayBuffer(blob) {
  return new Promise((resolve) => {
    // Blob 转 ArrayBuffer
    let reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    reader.onload = function () {
      resolve(reader.result)
    }
  })
}
</script>

<style lang="scss" scoped>
#cesiumContainer {
  width: 100vw;
  height: 100vh;
}
.popover-container {
  position: absolute;
  z-index: 1;
  padding: 5px;
  background: rgba(255, 255, 255, 0.4);
  color: #ffffff;
  transition: opacity 1s; /* 添加过渡效果 */
}
</style>
